package cn.controller;

import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.JsonSerializable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.common.ExceResult;
import cn.common.GridCommon;
import cn.common.LayTable;
import cn.common.PageString;
import cn.filter.LoginCheck;
import cn.kpi.entity.sys.OrgEntity;
import cn.kpi.entity.sys.RoleEntity;
import cn.kpi.entity.sys.UserEntity;
import cn.kpi.entity.usualassessment.UsAssTempCreateIndexEntity;
import cn.kpi.entity.usualassessment.UsAssTemplateEntity;
import cn.kpi.entity.usualassessment.UsAssTemplateIndexEntity;
import cn.kpi.service.sys.IOrgService;
import cn.kpi.service.usualassessment.IUsAssTemplateService;

@Controller
@RequestMapping("usualass")
public class UsualAssTemplateController extends BaseController {

	@Autowired
	private IUsAssTemplateService iUsAssTemplateService;
	
	@Autowired
	private IOrgService  iOrgService;

	@RequestMapping(value = "/template_list")
	public String TemplateList(Model model) {
		try {
			List<UsAssTemplateIndexEntity> lst = iUsAssTemplateService.GetTemplateIndexListRowSpan();
			model.addAttribute("lst", lst);

			String parentid = "";
			String usassid = "";
			for (int i = 0; i < lst.size(); i++) {
				UsAssTemplateIndexEntity entity = lst.get(i);
				usassid += entity.getAssindexid().toString() + ",";
				if (parentid.length() > 0) {
					String[] strarr = parentid.split(",");
					String last = strarr[strarr.length - 1];
					if (!last.equals(entity.getParentid().toString())) {
						parentid += entity.getParentid().toString() + ",";
					}
				} else {
					parentid += entity.getParentid().toString() + ",";
				}

			}

			PageString pagestring = new PageString();
			pagestring.setKeyword1(parentid.substring(0, parentid.length() - 1));
			pagestring.setKeyword2(usassid.substring(0, usassid.length() - 1));

			model.addAttribute("pagestring", pagestring);

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return "usualassessment/template_list";
	}
	
	
	@RequestMapping(value = "/template_list_alone")
	public String TemplateListAlone(Model model) {
//		try {
//			List<UsAssTemplateIndexEntity> lst = iUsAssTemplateService.GetTemplateIndexListRowSpan();
//			model.addAttribute("lst", lst);
//
//			String parentid = "";
//			String usassid = "";
//			for (int i = 0; i < lst.size(); i++) {
//				UsAssTemplateIndexEntity entity = lst.get(i);
//				usassid += entity.getAssindexid().toString() + ",";
//				if (parentid.length() > 0) {
//					String[] strarr = parentid.split(",");
//					String last = strarr[strarr.length - 1];
//					if (!last.equals(entity.getParentid().toString())) {
//						parentid += entity.getParentid().toString() + ",";
//					}
//				} else {
//					parentid += entity.getParentid().toString() + ",";
//				}
//
//			}
//
//			PageString pagestring = new PageString();
//			pagestring.setKeyword1(parentid.substring(0, parentid.length() - 1));
//			pagestring.setKeyword2(usassid.substring(0, usassid.length() - 1));
//
//			model.addAttribute("pagestring", pagestring);
//
//		} catch (Exception ex) {
//			ex.printStackTrace();
//		}
		return "usualassessment/template_list_alone";
	}
	
	@RequestMapping(value = "/template_list_alone_edit")
	public String TemplateListAloneEdit(Model model,Long templateid,Long groupid) {
		try{
			//List<UsAssTemplateIndexEntity> lst = iUsAssTemplateService.GetTemplateIndexListRowSpanByTempId(templateid);
			String where="";
			
			String orgids=this.GetOrgListByRole();
			where+=" AND byuserid IN (SELECT userid FROM t_sys_user WHERE szdw IN ("+orgids+")) AND groupid="+groupid+" ";
			
			List<UsAssTemplateIndexEntity> lst = iUsAssTemplateService.GetTemplateIndexListRowSpanByTempIdAndWhere(templateid,where);
			model.addAttribute("lst", lst);
			model.addAttribute("templateid", templateid);
			model.addAttribute("groupid", groupid);
			
			
			String parentid = "";
			String usassid = "";
			for (int i = 0; i < lst.size(); i++) {
				UsAssTemplateIndexEntity entity = lst.get(i);
				usassid += entity.getAssindexid().toString() + ",";
				if (parentid.length() > 0) {
					String[] strarr = parentid.split(",");
					String last = strarr[strarr.length - 1];
					if (!last.equals(entity.getParentid().toString())) {
						parentid += entity.getParentid().toString() + ",";
					}
				} else {
					parentid += entity.getParentid().toString() + ",";
				}

			}
			PageString pagestring = new PageString();
			pagestring.setKeyword1(parentid.substring(0, parentid.length() - 1));
			pagestring.setKeyword2(usassid.substring(0, usassid.length() - 1));
			model.addAttribute("pagestring", pagestring);
			
			if(templateid>0){
				UsAssTemplateEntity ustempentity=iUsAssTemplateService.GetUsAssTemplateListById(templateid);
				model.addAttribute("ustempentity", ustempentity);
			}
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		return "usualassessment/template_list_alone_edit";
	}
	
	@RequestMapping(value = "/templateindex_list")
	public String TemplateIndexList(Model model,Long templateid) {
		try {
			if(templateid>0){
				List<UsAssTempCreateIndexEntity> lst=iUsAssTemplateService.GetTemplateCreateIndexListRowSpan(templateid);
				model.addAttribute("lst", lst);
				String parentid = "";
				String usassid = "";
				for (int i = 0; i < lst.size(); i++) {
					UsAssTempCreateIndexEntity entity = lst.get(i);
					usassid += entity.getAssindexid().toString() + ",";
					if (parentid.length() > 0) {
						String[] strarr = parentid.split(",");
						String last = strarr[strarr.length - 1];
						if (!last.equals(entity.getParentid().toString())) {
							parentid += entity.getParentid().toString() + ",";
						}
					} else {
						parentid += entity.getParentid().toString() + ",";
					}

				}
				PageString pagestring = new PageString();
				pagestring.setKeyword1(parentid.substring(0, parentid.length() - 1));
				pagestring.setKeyword2(usassid.substring(0, usassid.length() - 1));
				model.addAttribute("pagestring", pagestring);
				
				
				UsAssTemplateEntity ustempentity=iUsAssTemplateService.GetUsAssTemplateListById(templateid);
				model.addAttribute("ustempentity", ustempentity);
			}
			else{
				List<UsAssTemplateIndexEntity> lst = iUsAssTemplateService.GetTemplateIndexListRowSpan();
				model.addAttribute("lst", lst);
				String parentid = "";
				String usassid = "";
				for (int i = 0; i < lst.size(); i++) {
					UsAssTemplateIndexEntity entity = lst.get(i);
					usassid += entity.getAssindexid().toString() + ",";
					if (parentid.length() > 0) {
						String[] strarr = parentid.split(",");
						String last = strarr[strarr.length - 1];
						if (!last.equals(entity.getParentid().toString())) {
							parentid += entity.getParentid().toString() + ",";
						}
					} else {
						parentid += entity.getParentid().toString() + ",";
					}

				}
				PageString pagestring = new PageString();
				pagestring.setKeyword1(parentid.substring(0, parentid.length() - 1));
				pagestring.setKeyword2(usassid.substring(0, usassid.length() - 1));
				model.addAttribute("pagestring", pagestring);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		model.addAttribute("templateid", templateid);
		return "usualassessment/templateindex_list";
	}

	@RequestMapping(value = "/templateindex_edit")
	public String TemplateEdit(Model model) {
		try {
			String where = " AND assindextype=0";
			List<UsAssTemplateIndexEntity> lst = iUsAssTemplateService.GetTemplateIndexListByWhere(where);
			model.addAttribute("lst", lst);
			
			
			
		} catch (Exception ex) {

		}
		return "usualassessment/templateindex_edit";
	}

	
	@RequestMapping(value = "/index_list")
	public String IndexList(Model model) {
		try{
			UserEntity userentity=this.GetLoginUser();
			List<OrgEntity> lstorg = iOrgService.GetOrgListByWhere(" AND orgtype=1 AND  orgparentid="+userentity.getSzdw());
			model.addAttribute("lstorg", lstorg);
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		
		return "usualassessment/index_list";
	}
	@RequestMapping(value = "/index_edit")
	public String IndexEdit(Model model,Long assindexid) {
		try {
			String where = " AND assindextype=0";
			if(this.GetLoginUserId()==0){
				where+=" AND byuserid=0";
			}
			else{
				String orgids=this.GetOrgListByRole();
				where+=" AND byuserid IN (SELECT userid FROM t_sys_user WHERE szdw IN ("+orgids+"))";
			}
			
			List<UsAssTemplateIndexEntity> lst = iUsAssTemplateService.GetTemplateIndexListByWhere(where);
			model.addAttribute("lst", lst);
			UsAssTemplateIndexEntity entity=new UsAssTemplateIndexEntity();
			if(assindexid>0){
			  entity=iUsAssTemplateService.GetIndexById(assindexid);
			}
			else{
				entity.setParentid(0L);
			}
			model.addAttribute("entity", entity);
			
			UserEntity userentity=this.GetLoginUser();
			
			List<OrgEntity> lstorg = iOrgService.GetOrgListByWhere(" AND orgtype=1 AND  orgparentid="+userentity.getSzdw());
			model.addAttribute("lstorg", lstorg);
			
		} catch (Exception ex) {

		}
		return "usualassessment/templateindex_edit";
	}
	
	@RequestMapping(value = "/template_list_alone_edit_new")
	public String TemplateListAloneEditNew(Model model,Long templateid) {
		try {
			List<OrgEntity> lstorg = iOrgService.GetOrgListByWhere(" AND orgtype=1 AND  orgparentid="+this.GetLoginUser().getSzdw());
			model.addAttribute("lstorg", lstorg);
			model.addAttribute("templateid", templateid);
			
			if(templateid>0){
				UsAssTemplateEntity ustempentity=iUsAssTemplateService.GetUsAssTemplateListById(templateid);
				model.addAttribute("ustempentity", ustempentity);
			}
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}
		return "usualassessment/template_list_alone_edit_new";
	}
	
	
	
	@RequestMapping(value = "/add_templateindex")
	public String AddTemplateindex(HttpServletRequest request, HttpServletResponse response) {
		try {
			UsAssTemplateIndexEntity entity = new UsAssTemplateIndexEntity();
			if(request.getParameter("assindexid")==null||request.getParameter("assindexid").equals("")){
				entity.setAssindexid(0L);
			}
			else{
				entity.setAssindexid(Long.parseLong(request.getParameter("assindexid")));
			}
			
			entity.setAssindextype(Integer.parseInt(request.getParameter("assindextype")));
			entity.setByuserid(this.GetLoginUserId());
			entity.setParentid(Long.valueOf(request.getParameter("parentid")));
			entity.setScore(Integer.parseInt(request.getParameter("score")));
			entity.setTemplateid(Long.valueOf(0));
			entity.setGroupid(Long.valueOf(request.getParameter("groupid")));
			if (entity.getAssindextype() == 1) {
				entity.setUassingredients(request.getParameter("uasscontent").trim());
				entity.setEvaluationstandard(request.getParameter("evaluationstandard").trim());
			} else {
				entity.setUasscontent(request.getParameter("uasscontent").trim());
			}

			entity.setSzdw(this.GetLoginUser().getSzdw());
			
			int iResult = 0;
			if(entity.getAssindexid()>0){
				iResult = iUsAssTemplateService.UpdateIndex(entity);
			}
			else{
				if(entity.getParentid()==0){
					entity.setScore(0);
				}
				iResult = iUsAssTemplateService.InsertTemplateIndexentity(entity);
			}
			

			return renderStringScript(response, "<script>window.parent.CloseDialog(" + iResult + ")</script>");
		} catch (Exception ex) {
			ex.printStackTrace();
			return renderStringScript(response, "<script>window.parent.CloseDialog(0)</script>");
		}
	}

	@RequestMapping(value = "/create_templateindex")
	public String CreateTemplateIndex(HttpServletRequest request, HttpServletResponse response) {
		try {
			String strtemplateid = request.getParameter("templateid");
//			if(strtemplateid==null||strtemplateid.length()<=0){
//				return renderStringScript(response, "<script>window.parent.CloseDialog(0,'参数有误')</script>");
//			}
			
			Long templateid=Long.parseLong(strtemplateid);
			
			
			String parentids = request.getParameter("parentids");
			String assindexids = request.getParameter("assindexids");

			String[] parentidsArr = parentids.split(",");
			String[] assindexidsArr = assindexids.split(",");

			Long flag = 0L;
			List<UsAssTempCreateIndexEntity> lst = new ArrayList<UsAssTempCreateIndexEntity>();
			
			Long byuserid=this.GetLoginUserId();
			for (int i = 0; i < assindexidsArr.length; i++) {
				if(request.getParameter("cb_"+ assindexidsArr[i])!=null){
					UsAssTempCreateIndexEntity entity = new UsAssTempCreateIndexEntity();
					entity.setAssindexid(Long.parseLong(assindexidsArr[i]));
					entity.setAssindextype(1);
					entity.setParentid(Long.parseLong(request.getParameter("parentid_" + assindexidsArr[i])));
					entity.setTemplateid(templateid);
					entity.setEvaluationstandard(request.getParameter("evaluationstandard_" + assindexidsArr[i]));
					entity.setScore(Integer.parseInt(request.getParameter("score_" + assindexidsArr[i])));
					entity.setUassingredients(request.getParameter("uassingredients_" + assindexidsArr[i]));
					entity.setUasscontent(request.getParameter("uasscontent_" + entity.getParentid()));
					entity.setByuserid(byuserid);
					lst.add(entity);
				}
			}
			
		if(lst.size()<=0){
			return renderStringScript(response, "<script>window.parent.CloseDialog(0,'请选择指标项')</script>");
		}
			UsAssTemplateEntity tempentity = new UsAssTemplateEntity();
			
			tempentity.setTemplatename(request.getParameter("templatename"));
			tempentity.setBegintime(Date.valueOf(request.getParameter("begintime")));
			tempentity.setEndtime(Date.valueOf(request.getParameter("endtime")));
			tempentity.setTemplatedes(request.getParameter("templatedes"));
			tempentity.setByuserid(byuserid);
			tempentity.setGroupid(Long.parseLong(request.getParameter("groupid")));
			tempentity.setSzdw(this.GetLoginUser().getSzdw());
			int iResult=0;
            if(templateid>0){
            	tempentity.setTemplateid(templateid);
            	//System.out.println(JSON.toJSONString(lst));
            	iResult=iUsAssTemplateService.UpdateUsAssTempEntity(lst, tempentity);
			}
			else{
				iResult = iUsAssTemplateService.CreateTemplateAndIndex(lst, tempentity);
			}

			
			return renderStringScript(response, "<script>window.parent.CloseDialog(" + iResult + ")</script>");
		} catch (Exception ex) {
			ex.printStackTrace();
			return renderStringScript(response, "<script>window.parent.CloseDialog(0)</script>");
		}
	}
	
	
	@LoginCheck(description = true)
	@ResponseBody
	@RequestMapping(value = "/get_list")
	public LayTable<UsAssTemplateEntity> GetList(HttpServletRequest request) {

		List<UsAssTemplateEntity> lst=null;
		LayTable<UsAssTemplateEntity> layTable=new LayTable<UsAssTemplateEntity>();
		try {
			String templatename = request.getParameter("templatename");
			
			String where="";
			if(templatename!=null&&templatename.length()>0){
				where+=" AND templatename LIKE '%"+templatename.trim()+"%'";
			}
			
			String orgids=this.GetOrgListByRole();
			where+=" AND byuserid IN (SELECT userid FROM t_sys_user WHERE szdw IN ("+orgids+"))";
			
			lst = iUsAssTemplateService.GetUsAssTemplateListByWhere(where);
			for (int i = 0; i < lst.size(); i++) {
				lst.get(i).setRowNum(i + 1);
			}
 
			int iCount=iUsAssTemplateService.GetUsAssTemplateListCountByWhere(where);
			layTable.setCode(0);
			layTable.setCount(iCount);
			layTable.setData(lst);
			
		} catch (Exception e) {
			layTable.setCode(500);
		}
		return layTable;
	}
	
	
	@LoginCheck(description = true)
	@ResponseBody
	@RequestMapping(value = "/get_index_list")
	public GridCommon<UsAssTempCreateIndexEntity> GetIndexList(HttpServletRequest request) {

		List<UsAssTempCreateIndexEntity> lst=null;
		GridCommon<UsAssTempCreateIndexEntity> countlist=new GridCommon<UsAssTempCreateIndexEntity>();
		try {
			
			String where="";
			String strgroupid=request.getParameter("groupid");
			String orgids=this.GetOrgListByRole();
			if(this.GetLoginUserId()==0){
				where+=" AND byuserid=0";
			}
			else{
				where+=" AND byuserid IN (SELECT userid FROM t_sys_user WHERE szdw IN ("+orgids+"))";
			}
			
			if(strgroupid!=null&&strgroupid.length()>0){
				where+=" AND groupid="+strgroupid;
			}
			
			Integer currentPage=Integer.parseInt(request.getParameter("CurrentPage"));
			Integer pageSize=Integer.parseInt(request.getParameter("PageSize"));
			int beginrow=(currentPage-1)*pageSize;
			int endrow=pageSize;
			
			String wherelimit=where+" ORDER BY groupid LIMIT "+beginrow+","+endrow;
			
			lst = iUsAssTemplateService.GetIndexListByWhere(wherelimit);
			
			
 
			countlist.setCountRecord(iUsAssTemplateService.GetIndexListCountByWhere(where));
			countlist.setCurrentPage(1);
			countlist.setPageSize(10);
			countlist.setItems(lst);
			countlist.setStatus(0);
			countlist.setMsg("");
			
		} catch (Exception e) {
			countlist.setCurrentPage(1);
			countlist.setPageSize(10);
			countlist.setItems(null);
			countlist.setStatus(1);
			countlist.setMsg("操作成功");
		}
		return countlist;
	}
	
	@ResponseBody
	@RequestMapping(value = "/delete_template")
	public ExceResult DeleteTemplate(HttpServletRequest request,HttpServletResponse response){
		ExceResult result=new ExceResult();
		result.setCode(400);
		result.setResult(0);
		try{
		 Long templateid=Long.parseLong(request.getParameter("templateid"));
		 int iResult=iUsAssTemplateService.DeleteUsTempEntity(templateid);
		 if(iResult>0){
				result.setCode(200);
				result.setResult(iResult);
				result.setMsg("操作成功");
			}
			else{
				result.setCode(300);
				result.setResult(iResult);
				result.setMsg("操作失败");
			}
		}
		catch(Exception ex){
			result.setCode(500);
			result.setResult(0);
			result.setMsg("操作异常");
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "/delete_index")
	public ExceResult DeleteIndex(HttpServletRequest request,HttpServletResponse response){
		ExceResult result=new ExceResult();
		result.setCode(400);
		result.setResult(0);
		try{
		 Long assindexid=Long.parseLong(request.getParameter("assindexid"));
		 Long parentid=Long.parseLong(request.getParameter("parentid"));
		 int iResult=iUsAssTemplateService.DeleteIndex(assindexid, parentid);
		 if(iResult>0){
				result.setCode(200);
				result.setResult(iResult);
				result.setMsg("操作成功");
			}
			else{
				result.setCode(300);
				result.setResult(iResult);
				result.setMsg("操作失败");
			}
		}
		catch(Exception ex){
			result.setCode(500);
			result.setResult(0);
			result.setMsg("操作异常");
		}
		return result;
	}

}
